<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="6">
          <!-- 搜索用户开始 -->
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @change="getUserList" @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
          <!-- 搜索用户结束 -->
        </el-col>
        <el-col :span="4">
          <!-- 添加用户开始 -->
          <el-button type="primary" @click="dialogFormVisible = true">添加用户</el-button>
          <!-- 添加用户结束 -->
        </el-col>
      </el-row>
      <el-table
        :data="userList"
        style="width: 100%"
        border
        stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column  prop="mobile" label="手机"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column  label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="getUserNewChange(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改人员 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="updateUserInfo(scope.row)"></el-button>
            <!-- 删除人员 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.id)"></el-button>
            <!-- 分配角色 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable=false>
              <el-button type="warning" icon="el-icon-s-tools" title="分配角色"  size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框开始 -->
    <el-dialog title="新增用户" :visible.sync="dialogFormVisible" @close="resetInf">
      <el-form ref="addFormErf" :model="userAddform" :rules="rules">
        <el-form-item label="账户" prop="username" :label-width="formLabelWidth">
          <el-input v-model="userAddform.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" :label-width="formLabelWidth">
          <el-input type="password" v-model="userAddform.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" :label-width="formLabelWidth">
          <el-input v-model="userAddform.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile" :label-width="formLabelWidth">
          <el-input v-model="userAddform.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="userAddVerifi()">确 定</el-button>
      </div>
    </el-dialog>
      <!-- 添加用户对话框结束 -->
    <!-- 修改用户对话框开始 -->
    <el-dialog title="修改用户" :visible.sync="updateUserVisible" @close="resetUpdateUser">
      <el-form ref="upUserRef" :model="updateUsers" :rules="rulesUpdate">
        <el-form-item label="账户" prop="username"  :label-width="formLabelWidth">
          <el-input  v-model="updateUsers.username"  disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" :label-width="formLabelWidth">
          <el-input v-model="updateUsers.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile" :label-width="formLabelWidth">
          <el-input v-model="updateUsers.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateUserInf()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改用户对话框结束 -->
  </div>
</template>
<script>
export default {
  data () {
    return {
      // 用户查询参数
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 每页显示多少条
        pagesize: 5
      },
      // 用户列表
      userList: [],
      // 用户总数
      total: 0,
      dialogFormVisible: false,
      userAddform: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      formLabelWidth: '120px',
      rules: {
        // 用户名验证规则
        username: [
          { required: true, message: 'Please input your username !', trigger: 'blur' },
          { min: 3, max: 10, message: 'Bigger than 3 and Smaller than 10 !', trigger: 'blur' }
        ],
        // 密码验证规则
        password: [
          { required: true, message: 'Please input your password !', trigger: 'blur' },
          { min: 6, max: 16, message: 'Bigger than 6 and Smaller than 16 !', trigger: 'blur' }
        ],
        email: [
          { required: true, message: 'Please input your password !', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: 'Please input your password !', trigger: 'blur' }
        ]
      },
      rulesUpdate: {
        email: [
          { required: true, message: 'Please input your password !', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: 'Please input your password !', trigger: 'blur' }
        ]
      },
      updateUserVisible: false,
      updateUsers: {}
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    // 获取角色列表
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听 pageSize 的值
    handleSizeChange (newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听 页码 值
    handleCurrentChange (newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 更改用户状态
    async getUserNewChange (newChange) {
      const { data: res } = await this.$http.put(`users/${newChange.id}/state/${newChange.mg_state}`)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      return this.$message.success(res.meta.msg)
    },
    // 新增用户
    userAddVerifi () {
      this.$refs.addFormErf.validate(async val => {
        console.log(val)
        if (!val) return
        const { data: res } = await this.$http.post('/users', this.userAddform)
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        // 对话框隐藏
        this.dialogFormVisible = false
        // 获取用户列表
        this.getUserList()
        // 成功消息
        return this.$message.success(res.meta.msg)
      })
    },
    // 清空新增用户输入框内容
    resetInf () {
      // 重置输入框内容
      this.$refs.addFormErf.resetFields()
    },
    // 修改之前，根据ID获取用户信息
    async updateUserInfo (row) {
      this.updateUserVisible = true
      const { data: res } = await this.$http.get('users/' + row.id)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.updateUsers = res.data
    },
    // 清空新增用户输入框内容
    resetUpdateUser () {
      // 重置输入框内容
      this.$refs.upUserRef.resetFields()
    },
    // 修改用户
    updateUserInf () {
      this.$refs.upUserRef.validate(async val => {
        if (!val) return
        const { data: res } = await this.$http.put('users/' + this.updateUsers.id, {
          email: this.updateUsers.email,
          mobile: this.updateUsers.mobile
        })
        if (res.meta.status !== 200) {
          return this.$message.error('123' + res.meta.msg)
        }
        // 对话框隐藏
        this.updateUserVisible = false
        // 获取用户列表
        this.getUserList()
        // 成功消息
        return this.$message.success(res.meta.msg)
      })
    },
    // 删除用户组件
    async deleteUser (uid) {
      // 获取弹框消息结果，捕获取消抛出的异常
      const resConfirm = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // resConfirm，确认得到结果 'confirm' , 取消得到结果 'cancel'
      // 取消的话 提示“已经取消删除”
      if (resConfirm !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      // 确认的话，开始删除操作
      const { data: res } = await this.$http.delete('users/' + uid)
      // 如果删除失败，进行提示
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      // 获取用户列表
      this.getUserList()
      // 成功消息
      return this.$message.success(res.meta.msg)
    }
  }
}
</script>
<style lang="less" scoped>
</style>
